
using BasicModuleWebApiJWTAuthorization.Model;
using BasicModuleWebApiJWTAuthorization.PermissionAuthorization;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Signalrs.context;
using Signalrs.HubModel;
using System.Text;
using Signalrs.Repositories;
using Microsoft.AspNetCore.Http.Features;

namespace Signalr
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();
            builder.Services.AddSignalR();
            //配置jwt认证
            builder.Services.AddAuthentication(optin =>
            {
                //配置jwt认证方案
                var deault = optin.DefaultAuthenticateScheme;
                optin.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                var defalut = optin.DefaultChallengeScheme;
                optin.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(option =>
            {
                //配置token认证方式  设置哪些字段为true 代表验证哪些字段
                option.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuer = true, //认证签发者 。生产token系统
                    ValidateAudience = true,//认证受用者 erp系统
                    ValidateLifetime = true,//认证生成token时间
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = "jwt", //认证签发者 。生产token系统
                    ValidAudience = "BasicModuleWebApiJWTAuthorization", //认证受用者 erp系统
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("R2XMnd6TQdYRUmR0cCfL9fk651Fb3kDI")) //认证生成token密钥
                };

                option.Events = new JwtBearerEvents
                {
                    //websocket 不支持自定义报文头
                    //我们需要把jwt通过url中的querystring传递
                    //然后在服务端的OnMessageReceived中，把querystring中的jwt读取出来，然后赋值给context.token
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        var path = context.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/maphub"))
                        {
                            context.Token = accessToken;
                        }
                        return Task.CompletedTask;
                    }
                };
            });
            builder.Services.AddTransient<ImportExecutor>();
            builder.Services.AddScoped<IUserRepository, UserRepository>();
            builder.Services.Configure<FormOptions>(options =>
            {
                options.MultipartBodyLengthLimit = 104857600 * 4; // 400MB
            });
            //注册授权处理器
            builder.Services.AddSingleton<IAuthorizationHandler, UserPermissionAuthodrizationHandler>();
            builder.Services.AddAuthorization(option =>
            {
                ////使用自定义授权策略
                option.AddPolicy("xxxxx", x =>
                {
                    ////添加自定义声明
                    x.AddRequirements(new UserPermissionAuthorizationRequirement("xxxxx"));
                });

            });
            // 添加 DbContext 到 DI 容器
            builder.Services.AddDbContext<AppDbContext>(options =>
                  options.UseMySql(
                          builder.Configuration.GetConnectionString("Default"),
                           new MySqlServerVersion(new Version(5, 7, 0))
                     ));
            //builder.Services.AddSignalR().AddStackExchangeRedis("127.0.0.1", options => { options.Configuration.ChannelPrefix = "Test1 "; }); 
            // 添加 CORS 服务，定义一个全开放策略
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("AllowVueClient", policy =>
                {
                    policy
                        .WithOrigins("http://localhost:5173")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials(); // 如果有身份验证、cookie 等
                });
            });

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            // 启用 CORS 策略
            app.UseCors("AllowVueClient");
            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseAuthorization();

            app.MapControllers();
            app.MapHub<ChatRoomHub>("/maphub/singlr").RequireCors("AllowVueClient");
            //app.MapHub<UploadHub>("/uploadHub");
            app.Run();
        }
    }
}
